const db = require('../../models/index');
const logger = require('../../utils/logger-util');
const { aes,md5 } = require('../../utils/crypto-util');
const { USER_STATE } = require('../../constants/system/user-constants');
const Users = db.users;
const tokenUtil = require('../../utils/token-util');
const GetIp = require('../../utils/clientlp-util');
const { baseURL } = require('../../config/multer-config');

// 登录
exports.login = (req, res) => {
    let userInfo = req.body
    //记录访客
    logger.info(`【IP】${(GetIp.getClientIp(req))}【登录】 userId:${userInfo.userId}- password:${userInfo.password}`);
    let userId = aes.de(userInfo.userId);
    Users.findOne({where: {userId: userId}})
    .then(data => {
        // 判断用户状态
        if(data.state == USER_STATE.BANNED) {
            return res.sendResultAto(null, 401, '账户已被禁用！请联系管理员');
        };
        let dbPassword = md5(userInfo.password);
        if(dbPassword === data.password) {
            let tokenUserInfo = {
                id: data.id,
                userId: userInfo.userId,
                password: userInfo.password,
            };
            // 生成token
            let token = tokenUtil.createToken(tokenUserInfo, 3600 * 24 * 3); // 有效期3天
            // data.avatar = baseURL+data.avatar;
            return res.sendResultAto({data, token}, 200, '登录成功');
        };
        logger.error('密码错误');
        res.sendResultAto(null, 401, '密码错误');
    }).catch(err => {
        logger.error(err);
        res.sendResultAto(null, 401, '用户不存在');
    })
};